package com.hg.oa.receiver;

import android.app.DownloadManager;
import android.content.ActivityNotFoundException;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;

/**
 * Created by fengxiang on 2016/10/9.
 */
public class DownloadReceiver extends BroadcastReceiver {
    final static String MINETYPE = "application/vnd.android.package-archive";

    @Override
    public void onReceive(Context context, Intent intent) {
        Bundle bundle = intent.getExtras();
        long downId = bundle.getLong(DownloadManager.EXTRA_DOWNLOAD_ID, 0);
        DownloadManager downloadManager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
        Uri filepath = downloadManager.getUriForDownloadedFile(downId);
        if (intent.getAction() == DownloadManager.ACTION_DOWNLOAD_COMPLETE) {
            Intent activityIntent = new Intent(Intent.ACTION_VIEW);
            activityIntent.setDataAndType(filepath, MINETYPE);
            activityIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            try {
                context.startActivity(activityIntent);
            } catch (ActivityNotFoundException ex) {
                Log.d(getClass().getName(), "no activity for " + MINETYPE, ex);
            }
        } else if (intent.getAction().equals(DownloadManager.ACTION_NOTIFICATION_CLICKED)) {
            try {
                Intent dm = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
                dm.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                context.startActivity(dm);
            } catch (ActivityNotFoundException ex) {
                Log.d(getClass().getName(), "no activity for " + MINETYPE, ex);
            }
        }

    }

}
